package com.dingwen.treasure.security.service;

import com.dingwen.treasure.security.dto.LoginUser;
import com.dingwen.treasure.security.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Objects;
import java.util.Set;

/**
 * 　PermissionService :权限管理
 * 　@author dingwen
 * 　@date 2022/6/24
 */
@Service("pm")
public class PermissionService {

    /**
     * 所有权限
     */
    private static final String ALL_PERMISSION = "*:*:*";

    /**
     * 是否包含某权限
     *
     * @param permission 准许
     * @return boolean
     */
    public boolean hasPerm(String permission) {

        if (StringUtils.isEmpty(permission)) {
            return Boolean.FALSE;
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (Objects.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) {
            return Boolean.FALSE;
        }
        return hasPermissions(loginUser.getPermissions(), permission);
    }

    /**
     * 判断是否包含权限
     *
     * @param permissions 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    private boolean hasPermissions(Set<String> permissions, String permission) {
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }
}
